<template>
  <div class="outter">
    <!-- 开头的添加搜索功能区 -->
    <div class="buttonsearch">
      <a-button type="primary" @click="addVisible = true"
        ><a-icon type="plus-circle" />新增管理人员</a-button
      >

      <div class="searchout">
        <a-button type="dashed" @click="reset">重置</a-button>
        <a-input-search
          style="width: 88%"
          placeholder="搜索菜品种类或菜品"
          enter-button
          @search="onSearch"
        ></a-input-search>
      </div>
    </div>
    <a-table
      :columns="columns"
      :pagination="false"
      :scroll="{ y: 400 }"
      :data-source="data"
      bordered
      :fixed="true"
      :loading="tableLoading"
      :defaultExpandAllRows="true"
    >
      <!-- 修改名称部分 -->
      <template
        v-for="col in ['name', 'password']"
        :slot="col"
        slot-scope="text, record"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="(e) => handleTchange(e.target.value, record, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <!-- 操作方法部分 -->
      <template slot="method" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a-button type="primary" @click="() => tsave(record)"
              >保存</a-button
            >
            <a-divider type="vertical" />
            <a-button @click="() => tcancel(record)">取消</a-button>
          </span>
          <span v-else>
            <a-button :disabled="editingKey !== ''" @click="() => tedit(record)"
              type="primary">修改</a-button
            >
            <a-divider type="vertical" />
            <a-popconfirm
              :disabled="editingKey !== ''"
              title="确定删除吗？"
              @confirm="() => deletet(record)"
            >
              <a-button :disabled="editingKey !== ''" type="danger">
                删除
              </a-button>
            </a-popconfirm>
          </span>
        </div>
      </template>
      <template slot="pricy" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="!record.editable">
            {{ record.pricy }}
          </span>
          <span v-else>
            <a-select
              :default-value="record.pricy"
              style="width: 120px"
              @change="(value)=>{selectChange(value,record)}"
            >
              <a-select-option value="经理"> 经理 </a-select-option>
              <a-select-option value="服务员"> 服务员 </a-select-option>
              <a-select-option value="大厨"> 大厨 </a-select-option>
            </a-select>
          </span>
        </div>
      </template>
      <!-- 上传照片部分 -->
      <template slot="img" slot-scope="text, record">
        <a-upload
          name="file"
          :multiple="true"
          accept="image/*"
          :data="
            (file) => {
              return { photo: file, foodId: record.id };
            }
          "
          action="http://8.130.49.254:8889/test"
          @change="
            (info) => {
              handleChange(info, record);
            }
          "
          :show-upload-list="false"
        >
          <a class="uploadimage" href="javascript:;">
            <div class="zhezhao">修改</div>
            <img
              :src="record.img"
              alt=""
              style="height: 40px; width: 40px; border-radius: 10px"
            />
          </a>
        </a-upload>
      </template>
      <!-- 子代个数部分 -->
      <span slot="child" slot-scope="text, record">{{
        record.child.length
      }}</span>
      <!-- 嵌套的子表部分 -->
    </a-table>
    <!-- 添加桌台弹出框 -->
    <a-modal
      title="添加管理人员"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="submitForm('RuleForm')"
      @cancel="handleCancel"
      okText="确认"
      cancelText="取消"
    >
      <a-form-model
        ref="RuleForm"
        :model="RuleForm"
        :rules="rule"
        v-bind="layout"
      >
        <a-form-model-item has-feedback label="姓名" prop="name">
          <a-input v-model="RuleForm.name" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="账号" prop="count">
          <a-input v-model="RuleForm.count" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="密码" prop="password">
          <a-input v-model="RuleForm.password" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="权限" prop="pricy">
          <a-select
              default-value="经理"
              style="width: 120px"
              @change="(value)=>{RuleForm.pricy=value}"
            >
              <a-select-option value="经理"> 经理 </a-select-option>
              <a-select-option value="服务员"> 服务员 </a-select-option>
              <a-select-option value="大厨"> 大厨 </a-select-option>
            </a-select>
        </a-form-model-item>
        <a-form-model-item has-feedback label="头像" prop="img">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept="image/*"
            :data="
              (file) => {
                return { photo: file, name: RuleForm.value };
              }
            "
            action="http://8.130.49.254:8889/test"
            @change="handleaddChange"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              alt="avatar"
              style="width: 128px; height: 128px"
            />
            <div v-else>
              <a-icon :type="addloading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
// 定义四列属性
const columns = [
  {
    title: "管理员姓名",
    dataIndex: "name",
    width: "10%",
    align: "center",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "管理员账号",
    dataIndex: "count",
    width: "20%",
    align: "center",
    scopedSlots: { customRender: "count" },
  },
  {
    title: "密码",
    dataIndex: "password",
    width: "20%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "password" },
  },
  {
    title: "头像",
    dataIndex: "img",
    width: "10%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "img" },
  },
  {
    title: "权限身份",
    dataIndex: "pricy",
    width: "20%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "pricy" },
  },
  {
    title: "操作",
    dataIndex: "method",
    align: "center",
    scopedSlots: { customRender: "method" },
  },
];

const data = [];

data.push({
  key: 1,
  id: 1,
  name: `李哥`,
  count: "admin",
  password: "123456",
  img: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
  pricy: "经理",
  method: {},
});
data.push({
  key: 2,
  id: 2,
  name: `卢哥`,
  count: "asd",
  password: "123456",
  img: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
  pricy: "服务员",
  method: {},
});
data.push({
  key: 3,
  id: 3,
  name: `周哥`,
  count: "asasdd",
  password: "123456",
  img: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
  pricy: "大厨",
  method: {},
});

export default {
  data() {
    // 添加菜单类别判断
    let validateNameValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    let validateCountValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else if (value.length > 13) {
        callback(new Error("账号不应该过长"));
      } else if (
        this.data.some((item) => {
          return item.count == value;
        })
      ) {
        callback(new Error("账号已存在"));
      } else {
        callback();
      }
    };
    let validatePasswordValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入初始密码"));
      } else {
        callback();
      }
    };
    //上传弹出框图片判断-共享
    let validateImg = (rule, value, callback) => {
      if (this.imageUrl === "") {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      //form
      RuleForm: {
        name: "",
        count: "",
        password: "",
        pricy:"经理"
      },
      //form规则
      rule: {
        name: [
          { required: true, validator: validateNameValue, trigger: "change" },
        ],
        count: [
          { required: true, validator: validateCountValue, trigger: "change" },
        ],
        password: [
          {
            required: true,
            validator: validatePasswordValue,
            trigger: "change",
          },
        ],
        img: [{ required: true, validator: validateImg, trigger: "blur" }],
      },
      //弹出框布局
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      //上传弹出框图片loading-共享
      addloading: false,
      //添加菜类框是否可见
      addVisible: false,
      //表格Loading
      tableLoading: false,
      //确认提交表单loading-共享
      confirmLoading: false,

      //表格所需
      data,
      columns,
      //现在在修改的key
      editingKey: "",
      //弹出框的图片src-共享
      imageUrl: "",

      cachedata: [],
    };
  },
  mounted() {
    //创建缓存数据，缓存数据用来在修改取消时恢复
    this.refreshCachedata();
  },
  methods: {
    refreshCachedata() {
      this.cachedata = JSON.parse(JSON.stringify(this.data));
    },
    //修改的四个关键方法
    handleTchange(value, record, column) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      record[column] = value;
      this.data = newData;
    },
    tedit(record) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      this.editingKey = record.key;
      record.editable = true;
      this.data = newData;
    },
    tsave(record) {
      const newData = [...this.data];

      let tarr = Object.values(record);
      let message = "";
      for (let i = 0; i < tarr.length; i++) {
        if (tarr[i] === "") {
          message = "不可有修改项为空！";
          break;
        }
      }
      if (message != "") {
        this.$message.warn(message);
        return;
      }

      delete record.editable;
      this.data = newData;
      this.refreshCachedata();
      this.editingKey = "";
    },
    tcancel(record) {
      //不管是[...this.cachedata]还是object.assign整个付过去都会是浅拷贝，我这个效率最低但最省事
      this.editingKey = "";
      delete record.editable;
      this.data = JSON.parse(JSON.stringify(this.cachedata));
    },
    //查找时

    //处理
    handleChange(info, record) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        console.log(record);
        record.img = info.file.response;
        this.$message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
    },
    handleaddChange(info) {
      this.addloading = true;
      if (info.file.status === "done") {
        this.imageUrl = info.file.response;
        this.addloading = false;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
    },

    //提交表单时
    submitForm(formName) {
      let thing;

      thing = {
        key: this.RuleForm.name,
        id: this.RuleForm.name,
        name: this.RuleForm.name,
        count: this.RuleForm.count,
        password: this.RuleForm.password,
        img: this.imageUrl,
        pricy: this.RuleForm.pricy,
      };

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          setTimeout(() => {
            this.confirmLoading = false;
            this.data.push(thing);
            this.refreshCachedata();
            this.$message.success("成功添加");
            this.addVisible = false;
            this.addFoodVisible = false;
            this.$refs[formName].resetFields();
          }, 500);
          this.imageUrl = "";
        } else {
          console.log("添加失败");
          return false;
        }
      });
    },

    //两个弹出框的取消都是这个
    handleCancel() {
      this.addVisible = false;
    },
    selectChange(value,record){
      record.pricy=value
    },
    onSearch() {},
    //点击重置按钮时
    reset() {},
    //点击删除按钮时
    delete() {},
  },
};
</script>

<style scoped>
.outter {
  padding: 20px 10px;
}
.bottonheader {
  widows: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.buttons {
  width: 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.nima {
  width: 100%;
  height: 420px;
  background: rgb(217, 220, 223);
}

.editable-row-operations a {
  margin-right: 8px;
}
.buttonsearch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  margin-bottom: 25px;
}
.uploadimage {
  font-size: 1px;
  position: relative;
  /* transition: all 1s; */
}
.zhezhao {
  opacity: 0;
  background-color: rgb(95, 74, 74);
  transition: all 0.5s;
  color: aliceblue;
  position: absolute;
  width: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 10px;
}
.uploadimage:hover .zhezhao {
  opacity: 0.6;
}
.searchout {
  width: 50%;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
